$(function(){
    $("#form-user-assign_role").validate({
        onkeyup:false,
        focusCleanup:true,
        success:"",
        submitHandler:function(form){
        	var roleIdStr = getSelectRoleId();
        	var userId = $("#userId").val();
        	var appId = $("#appId").val();
        	var options = {
                type: $(form).attr("method"),
                url: $(form).attr("action"),
                success : formResponse,
                data : {
                	"roleIds" : roleIdStr,
                	"userId" : userId,
                	"appId" : appId
                },
                dataType: 'json',  
                error : function(xhr, status, err) {
                }  
            };
            $(form).ajaxSubmit(options);
        }
    });
    
    $("#appId").change(function(){
    	$("#roleDivTemp").html("");
    	$("#roleDiv").attr("style","text-align:center;");
    	$("#roleDiv").html("<img src='" + $("#cdnStaticResourcesPath").val() + "/resources/images/loading.gif'/><span style='margin-left:5px;vertical-align:middle;'>角色列表加载中...</span>");
    	//加载角色列表
    	loadAppRole();
    });
});

window.onload = function(){
	$("#roleDivTemp").html("");
	//加载应用所有的角色列表
    loadAppRole();
}
/**
 * 默认加载显示选中的应用对应的角色列表
 */
function loadAppRole(){
	var appId = $("#appId").val();
	$.ajax({
		async : true,
		type: "get",
        url: $("#getAppRoleListUrl").val(),
        data : {
        	"appId" : appId
        },
        dataType: 'json',
        success : function(result){
        	if(result != null && result != undefined && result.length > 0) {
        		$("#roleDivTemp").append("<br/>");
        		for(var i = 0; i < result.length; i++){
        			var roleObj = result[i];
        			var str = "<input style='margin-left:20px;' type='checkbox' lang='roleId_" + roleObj.id + "' name='userRoleId' value='" + roleObj.id + "' /> " + roleObj.name;
        			$("#roleDivTemp").append(str);
        			if(i % 6 == 0 && i > 0){
        				$("#roleDivTemp").append("<br/><br/>");
        			}
        		}
        		
        		//加载用户在应用下的角色列表,用于checkbox页面加载完毕后的选中状态
            	loadAppUserRole();
        	}else{
        		$("#roleDiv").html("<span style='color:red;'>未查询到该应用下的角色数据</span>");//清空
        	}
        }
	});
}

/**
 * 获取用户在该应用下角色列表
 */
function loadAppUserRole(){
	var appId = $("#appId").val();
	var userId = $("#userId").val();
	$.ajax({
		async : true,
		type: "get",
        url: $("#getAppRoleListUrl").val(),
        data : {
        	"appId" : appId,
        	"userId" : userId
        },
        dataType: 'json',
        success : function(result){
        	if(result != null && result != undefined && result.length > 0) {
        		
        		//循环遍历，将当前用户在应用下的角色进行checked选中
        		for(var i = 0; i < result.length; i++){
        			var roleObj = result[i];
        			$("input[lang='roleId_" + roleObj.id + "']").attr("checked","checked");
        		}
        		$("#roleDiv").attr("style","text-align:left;");
        	}else{
        		$("#roleDiv").attr("style","text-align:center;");
        	}
        	$("#roleDiv").html("");//清空
    		$("#roleDiv").html($("#roleDivTemp").html());
        }
	});
}


//获取选择的角色ID列表，逗号拼接成字符串
function getSelectRoleId() {
    var selRoles = $("#roleDiv input[name='userRoleId']:checked");
    var roleIdStr = "";
    if(selRoles != undefined && selRoles.length > 0){
    	for(var i = 0; i < selRoles.length; i++){
    		var appId = $(selRoles[i]).val();
    		roleIdStr += appId;
    		if(i < selRoles.length - 1){
    			roleIdStr += ",";
    		}
    	}
    }
    return roleIdStr;
}

/*表单回调函数*/
function formResponse(responseText, statusText){
    if(responseText.code == 200){
        layer.msg("成功分配角色,2秒后自动关闭窗口", {
            shift: 2,
            time : 2000,
            icon: 6
        },function(){
        	//关闭弹出框
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        });
        
        $("#searchBtn", parent.document).click();
    }else{
        layer.msg(responseText.msg, {
            shift: 2,
            icon: 5
        });
        return false;
    }
}
